<template>
  <div>
    <div style="margin-top: 40px; margin-left:50px; font-size:20px;color:#cccccc; ">
      <span>任务管理</span>
    </div>
    <div style="width:100%;display: flex; justify-content: center;">
      <div class="parentdhumanTaskBox">
        <div style="width:100%;height:20px; ">
        </div>
        <div v-for="(item, index) in list" :key="index">
          <div class="dhumanTaskBox">
            <!--该部分处理任务和状态，根据status的内容 step中显示处理的状态，
              如果step的状态是1 预处理，则判断process = 0,则显示预处理中
              如果step的状态是1 预处理，则判断process = 1,预处理完成
              如果step的状态2 任务处理，则判断process = 0,则显示任务处理
              如果step的状态2 任务处理，则判断process = 1,则显示任务完成
              如果step的状态2 任务处理，则判断process = -1,则显示任务错误
            -->
            <div class="task-status">
              <div><i class="el-icon-info" style="font-size: 18px; margin-left:8px;color:#605f5f; cursor: pointer;" title="处理日志查询" @click="queryTaskLogs(item.uuid1)" /></div>
              <div style="display: flex; margin-right:7px;">
                <div v-show="(item.step == 1 && item.process != 100 && item.status == 1)?true:false" class="task-status-item">
                  <div class="bluedot" /><div>任务处理中</div>
                </div>
                <div v-show="(item.step == 1 && item.process == 100 && item.status == 1)?true:false" class="task-status-item">
                  <div class="greendot" /><div>处理完成</div>
                </div>
                <div v-show="(item.status == -1)?true:false" class="task-status-item">
                  <div class="reddot" /><div>出错了...</div>
                </div>
              </div>
            </div>
            <div class="thumbnail_box">
              <div style="width:238px; height:230px;; display:flex; justify-content: center; align-items: center;padding:1px;">
                <img :src="item.avatar" :onerror="defaultImg" style="max-width:236px; max-height:228px">
              </div>
            </div>
            <div style="height:40px; width:100%;margin-top:5px; overflow: hidden; float:left; background-color: #404040;">
              <div style="width:95%; height:40px;overflow: hidden; padding:5px;text-align: left;">
                {{ item.tname }}
              </div>
            </div>
            <div style="height:30px; width:100%; display: flex; justify-content: space-between;">
              <div style="display: flex;  justify-content:lex-start; margin:15px; color: #989595;">
                <div><i class="el-icon-time" style="font-size:18px;" /></div>
                <div style="white-space: nowrap; font-size: 12px; margin-left: 6px;margin-top: 4px;">
                  {{ DatetimeToYDMH(item.ctime) }}</div>
              </div>
              <div style="width: 100px; margin-top:10px; display:flex; ">
                <div style="width:40px;"><a title="删除任务" @click="delDhumanTask(item.id)"><i class="el-icon-delete el-icon-btn" /></a></div>
                <div style="width:60px;"><a title="任务详情" @click="queryTaskInfo(item.id)"><i class="el-icon-tickets el-icon-btn" /></a>&nbsp;
                <a title="下载处理结果" @click="downloadResult(item.id)"><i class="el-icon-download  el-icon-btn" /></a>&nbsp;</div>
              </div>
            </div>
          </div>
        </div>
        <div style="width:100%;color:azure; float:right; margin-top:30px; margin-bottom: 50px;">
          <el-pagination
            background
            :current-page="tablePage.pageNum"
            :page-sizes="tablePage.pageSize"
            :page-size="tablePage.pageSize"
            layout="prev, pager, next"
            :total="tablePage.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>
    <LogDialog v-if="logDialogVisiable" ref="logDialog" />
    <dhumanTaskInfoDialog v-if="dtinfoDialogVisiable" ref="dhumanTaskInfoDialog" />
  </div>
</template>
<script>
import dimg from '@/assets/image/defaultimg.png'
import { getTaskList as getList, getTaskStatus, delTask } from '@/api/dhuman'
import LogDialog from './logDialog.vue'
import dhumanTaskInfoDialog from './dhumanTaskInfo.vue'
import user from '@/store'

export default {
  name: 'SubtitleTask',
  components: { LogDialog, dhumanTaskInfoDialog },
  data() {
    return {
      tablePage: {
        pageNum: 1, // 第几页
        pageSize: 12, // 每页多少条
        total: 0, // 总记录数
        pageSizes: []
      },
      defaultImg: 'this.src="' + dimg + '"',
      dhumanTimer: null,
      fileType: 'video/mp4',
      list: null,
      listLoading: true,
      corpid: -1,
      currentPage: 1,
      logDialogVisiable: false,
      dtinfoDialogVisiable: false
    }
  },
  created() {
    // this.fetchData(1)
  },
  mounted() {
    this.fetchData(0)
    this.dhumanTimer = setInterval(this.getTaskStatus, 30000)
  },
  beforeDestroyed() {
    if (this.dhumanTimer) {
      clearInterval(this.dhumanTimer) // 在组件销毁前清除定时器
      this.dhumanTimer = null
    }
  },
  methods: {
    fetchData(currentPage) {
      this.listLoading = true
      const params = {
        corpid: user.getters.corpid,
        uid: user.getters.uid,
        nickname: user.getters.name,
        pagesize: this.tablePage.pageSize,
        page: currentPage
      }
      this.tablePage.pageNum = currentPage
      this.list = null
      getList(params).then(response => {
        let start
        this.list = response.data.data
        // 在此判断一下是否为空的记录，如果为空，并且currentPage大于1，则获取前一个;
        if (this.list.length == 0) {
          if (currentPage > 1) {
            this.fetchData(currentPage - 1)
          }
        }
        this.tablePage.total = response.length
        const isFirst = this.tablePage.total < this.tablePage.pageSize
        const isLast = Math.ceil(this.tablePage.total / this.tablePage.pageSize) === 1
        this.start = 0
        const end = isFirst || isLast ? this.start + (this.tablePage.total % this.tablePage.pageSize) : this.start + this.tablePage.pageSize
        this.listLoading = false
        this.currentPage = currentPage
      })
    },
    // 根据list中的数据，来查询相关的状态
    getTaskStatus() {
      if (this.list == null) {
        console.log('clip的list是空')
        return
      }
      for (var i = 0; i < this.list.length; i++) {
        var item = this.list[i] // 获取当前索引位置的元素
        // 在这里处理每个元素，例如打印其内容
        if (item.status == 1) {
          const param = {
            corpid: user.getters.corpid,
            uid: user.getters.uid,
            taskid: item.id
          }
          getTaskStatus(param).then(response => {
            // 返回的是该记录的当前的值
            var data = response.data.data
            if (data.length == null) return
            if (data.length > 0) {
              var dat = data[0]
              // console.log(dat)
              // 如果有返回值，则把list中的对应记录进行变更;
              for (var j = 0; j < this.list.length; j++) {
                var item1 = this.list[j]
                if (item1.id == dat.id) {
                  item1.status = dat.status
                  item1.step = dat.step
                  item1.process = dat.process
                  item1.thumbnail = dat.thumbnail
                  item1.outurl = dat.outurl
                  this.$set(this.list, j, item1)
                  break
                }
              }
            }
          })
        }
      }
    },
    // 删除指定的任务
    delDhumanTask(taskid) {
      this.$confirm('确定要删除吗？', '提示', {
        type: 'warning'
      }).then(() => {
        const param = {
          corpid: user.getters.corpid,
          uid: user.getters.uid,
          taskid: taskid
        }
        delTask(param).then(response => {
          this.fetchData(this.currentPage)
        })
      // 返回的是该记录的当前的值
      }).catch(() => {
      })
    },
    handleCurrentChange(currentPage) {
      this.fetchData(currentPage)
    },
    handleSizeChange(pageSize) {
      this.tablePage.pageSize = pageSize
      // 在此刷新数据
    },
    hiddenPlayBtn(id) {
      var dom = document.getElementById('playBtn' + id)
      dom.style.display = 'none'
    },
    confirmTaskStatus(i) {
      console.log(i)
      console.log(this.list)
      var item = this.list[i]
      console.log(item)
      var status = item.status
      var process = item.process
      var step = item.step
      if (step === 1 && status < 1) {
        this.alertMessage('预处理错误，请重新上传文件处理')
        return false
      }

      if (process != 100) {
        this.alertMessage('任务处理中，请稍候。。。')
        return false
      }
      return true
    },
    alertMessage(msg) {
      this.$alert(msg, '说明', {
        confirmButtonText: '确定',
        callback: action => {
          return
        }
      })
    },
    // 查询任务运行的日志
    queryTaskLogs(uuid) {
      this.logDialogVisiable = true
      this.$nextTick(() => {
        this.$refs.logDialog.init(uuid)
      })
    },
    // 查询任务信息
    queryTaskInfo(taskid) {
      this.dtinfoDialogVisiable = true
      this.$nextTick(() => {
        this.$refs.dhumanTaskInfoDialog.init(taskid)
      })
    },
    downloadResult(id){
      var item = null
      for(var i = 0; i < this.list.length; i++){
        if(id == this.list[i]["id"]){
          item = this.list[i]
        }
      }
      if(item != null) {
        var step = item["step"]
        var process = item["process"]
        var status = item["status"]
        var outurl = item["outurl"]
        if(status !== 1){
          this.alertMessage('任务出错了，请查看处理日志..')
          return false          
        }
        if(step != 1 || process != 100){
          this.alertMessage('任务进行中，请稍候...')
          return false          
        }
        else {
          window.open(outurl, '_self');
        }
      }
    },
    DatetimeToYDMH(dateTimeStr) {
      const date = new Date(dateTimeStr)
      // 验证日期是否有效
      if (isNaN(date.getTime())) {
        throw new Error('Invalid date time string')
      }
      // 获取月和日
      const month = String(date.getMonth() + 1).padStart(2, '0') // getMonth() 返回的是从0开始的月份
      const day = String(date.getDate()).padStart(2, '0')
      // 获取时和分
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      // 拼接成所需的格式
      return `${month}-${day} ${hours}:${minutes}`
    },
    formatSeconds(seconds) {
      var hours = Math.floor(seconds / 3600)
      var minutes = Math.floor((seconds % 3600) / 60)
      var secs = seconds % 60

      hours = (hours < 10) ? '0' + hours : hours
      minutes = (minutes < 10) ? '0' + minutes : minutes
      secs = (secs < 10) ? '0' + secs : secs

      return hours + ':' + minutes + ':' + secs
    }
  }
}
</script>
<style>
.parentdhumanTaskBox {
  color: #f1efef;
  font-size: 14px;
  width: 1560px;
  margin: 0 auto;
  display: flex;
  flex-wrap: wrap;
  justify-content: None;
  min-height:300px;
}
.dhumanTaskBox {
  width: 240px;
  height: 350px;
  border: 1px solid #606060;
  margin:10px;
}

.reddot {
  width: 15px;
  height: 13px;
  background-color: red;
  border-radius: 50%;
}
.reddot {
  width: 10px;
  height: 10px;
  margin-top: 1px;
  margin-right: 4px;
  background-color: red;
  border-radius: 50%;
}
.greendot {
  width: 10px;
  height: 10px;
  margin-top: 1px;
  margin-right: 4px;
  background-color: yellowgreen;
  border-radius: 50%;
}
.bluedot {
  width: 10px;
  height: 10px;
  margin-top: 1px;
  margin-right: 4px;
  background-color: rgb(151, 168, 244);
  border-radius: 50%;
}

.thumbnail_box {
  height: 230px;
  width: 238px;
  background: #242424;
  display: flex;
  flex-direction: row-reverse;
}
.el-icon-btn {
    font-size: 16px; /* 或者其他你想要的大小 */
    color: gray;
    padding:3px;
    border: 1px solid gray;
    border-radius: 3px
}
.no-hover-events {
    pointer-events: none;
}
.el-icon-btn:hover {
    color: #f7f5f5;
    border: 1px solid #f7f5f5;
    cursor: pointer;
}
.task-loading {
  width: 240px;
  height: 240px;
  z-index: 2;
  position:absolute;
}
.task-loading-itag {
  font-size:50px;
}
.task-status {
  display: flex;
  justify-content: space-between;
  width: 100%;
  height: 20px;
  margin-top:5px;
  overflow: hidden;
}
.task-status-item {
  min-width: 50px;
  margin-top:3px;
  font-size: 13px;
  display:flex;
  justify-content: flex-start;
}
</style>
